package org.scc.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.scc.model.Resource;
import org.scc.model.Role;
import org.scc.model.User;
import org.scc.service.ResourceService;
import org.scc.service.RoleService;

public class RoleAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private RoleService roleService;
	private ResourceService resourceService;
	private Role role;
	public RoleAction(){
		roleService = new RoleService();
		resourceService = new ResourceService();
	}
	
	public void listRoles(){
		List<Role> roles = roleService.findAll();
		responeString(getRoleJson(roles));
	}
	
	private String getRoleJson(List<Role> roles){
		JSONArray arr = new JSONArray();
		JSONObject obj = null;
		for(Role role : roles){
			obj = new JSONObject();
			obj.put("id", role.getId() );
			obj.put("name", role.getName() );
			obj.put("scope", role.getScopeText() );
			obj.put("opt", getRoleResText(role.getId(), role.getScope() == Role.SCOPE_ALL) );
			arr.add(obj);
		}
		return arr.toString();
	}
	
	public String initEditPage(){
		if(id != 0){
			role = roleService.load(id);
		}
		return SUCCESS;
	}

	public void editRole(){
		if(role.getId() == 0){
			roleService.add(role);
		} else {
			roleService.update(role);
		}
		responseSuccess();
	}
	
	public void deleteRole(){
		roleService.delete(ids);
		responseSuccess();
	}
	
	public void listRoleRes(){
		List<Resource> resources = roleService.findResource(id);
		responeString(getResourceJson(resources));
	}
	
	private String getResourceJson(List<Resource> resources){
		JSONArray arr = new JSONArray();
		JSONObject obj = null;
		for(Resource resource : resources){
			obj = new JSONObject();
			obj.put("id", resource.getId() );
			obj.put("name", resource.getName() );
			obj.put("url", resource.getUrl() );
			obj.put("level", resource.getLevelText() );
			arr.add(obj);
		}
		return arr.toString();
	}
	
	
	private String getRoleResText(int id, boolean all){
		StringBuffer sb = new StringBuffer();
		sb.append("<a href='#' title='角色资源管理' onclick='editRoleRes(").append(id).append(")'>");
		sb.append("<img src='../easyui/themes/icons/table.png' style='border:0'/></a>");
		sb.append("&nbsp;&nbsp;");
		if(!all){
			sb.append("<a href='#' title='角色人员管理' onclick='editRoleUser(").append(id).append(")'>");;
			sb.append("<img src='../easyui/themes/icons/users.png' style='border:0'/></a>");
		}else {
			sb.append("<div  style='width: 16px;height: 16px;display: inline-block;'></div>");
		}
		return sb.toString();
	}
	
	/**
	 * 取得用户的角色的资源
	 * 
	 */
	public void getUserRoleRes(){
		User currentUser = getCurrentUser();
		if(currentUser.getUsername().equals("M1000")){//admin
			responeString( getFirstLevelJSON().toString() );
		} else {
			List<Resource> resources = new ArrayList<Resource>();
			List<Role> roles = new ArrayList<Role>();
			//取得全部人员类型的角色
			roles.addAll( roleService.findScopeAll() );
			//取得指定人员类型中我的角色
			roles.addAll( roleService.findUserRoles( currentUser.getId() ) );
			for(Role role : roles){
				resources.addAll( roleService.findResource( role.getId() ) );
			}
			responeString( getResStr(resources) );
		}
	}
	
	private String getResStr(List<Resource> resources){
		Map<Resource, List> resMap = new HashMap<Resource, List>();
		List<Resource> resList = null;
		for(Resource res : resources){
			if(resMap.containsKey(res.getParentRes())){
				resList.add(res);
			} else {
				resList = new ArrayList<Resource>();
				resMap.put(res.getParentRes(), resList);
			}
		}
		JSONArray flArr = new JSONArray();
		JSONObject flObj = null;
		Iterator<Resource> it = resMap.keySet().iterator();
		Resource flRes = null;
		
		JSONArray slArr = null;
		JSONObject slObj = null;
		while(it.hasNext()){
			flRes = it.next();
			flObj = new JSONObject();
			flObj.put("id",  flRes.getId());
			flObj.put("text", flRes.getName() );
			flObj.put("url", flRes.getUrl() );
			
			resList = resMap.get(flRes);
			slArr = new JSONArray();
			for(Resource slRes : resList){
				slObj = new JSONObject();
				slObj.put("id",  slRes.getId());
				slObj.put("text", slRes.getName() );
				slObj.put("url", slRes.getUrl() );
				slArr.add(slObj);
			}
			flObj.put("children", slArr);
			
			flArr.add(flObj);
		}
		return flArr.toString();
	}
	
	private JSONArray getFirstLevelJSON(){
		List<Resource> resources = resourceService.findFirstLevel();
		JSONObject fLres = null;
		JSONArray resArr = new JSONArray();
		for(Resource res : resources){
			fLres = new JSONObject();
			fLres.put("id", res.getId() );
			fLres.put("text", res.getName() );
			fLres.put("url", res.getUrl() );
			fLres.put("children", getSecondLevelJSON(res.getId()));
			resArr.add(fLres);
		}
		return resArr;
	}
	
	private JSONArray getSecondLevelJSON(int id){
		List<Resource> resources = resourceService.findSecondLevel(id);
		JSONObject sLres = null; 
		JSONArray nodeArr = new JSONArray();
		for(Resource res : resources){
			sLres = new JSONObject();
			sLres.put("id", res.getId() );
			sLres.put("text", res.getName() );
			sLres.put("url", res.getUrl() );
			
			nodeArr.add(sLres); 
		}
		return nodeArr;
	}
	
	public void addRoleRes(){
		roleService.addResource(id, ids);
		responseSuccess();
	}
	
	public void removeRoleRes(){
		roleService.removeResource(id, ids);
		responseSuccess();
	}
	
	public void addRoleUsers(){
		roleService.addUsers(id, ids);
		responseSuccess();
	}
	
	public void removeRoleUsers(){
		roleService.removeUsers(id, ids);
		responseSuccess();
	}
	
	public void listRoleUsers(){
		List<User> users = roleService.findRoleUsers(id);
		responeString(getRoleUserJSON(users));
	}
	
	private String getRoleUserJSON(List<User> users){
		JSONArray arr = new JSONArray();
		JSONObject obj = null;
		for(User user : users){
			obj = new JSONObject();
			obj.put("id", user.getId());
			obj.put("name", user.getName());
			obj.put("username", user.getUsername());
			arr.add(obj);
		}
		return arr.toString();
	}
	
	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	
}
